from flask import Flask, render_template, request, jsonify
import json
import os
from datetime import datetime

app = Flask(__name__)

# 数据文件路径
DATA_FILE = 'data/links.json'

# 确保数据目录存在
if not os.path.exists('data'):
    os.makedirs('data')

# 初始化数据文件
if not os.path.exists(DATA_FILE):
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump({"links": [], "categories": [], "tags": []}, f, ensure_ascii=False, indent=2)

def load_data():
    """加载数据"""
    try:
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except:
        return {"links": [], "categories": [], "tags": []}

def save_data(data):
    """保存数据"""
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/api/data')
def get_data():
    """获取所有数据"""
    return jsonify(load_data())

@app.route('/api/links', methods=['POST'])
def add_link():
    """添加链接"""
    data = load_data()
    link_data = request.json
    
    # 生成唯一ID
    link_id = str(int(datetime.now().timestamp()))
    link_data['id'] = link_id
    link_data['created_at'] = datetime.now().isoformat()
    
    data['links'].append(link_data)
    save_data(data)
    
    return jsonify({'success': True, 'link': link_data})

@app.route('/api/links/<link_id>', methods=['PUT'])
def update_link(link_id):
    """更新链接"""
    data = load_data()
    link_data = request.json
    
    # 处理数字和字符串类型的ID匹配
    for i, link in enumerate(data['links']):
        if str(link['id']) == str(link_id):
            link_data['id'] = link['id']  # 保持原有ID类型
            link_data['updated_at'] = datetime.now().isoformat()
            data['links'][i] = link_data
            save_data(data)
            return jsonify({'success': True, 'link': link_data})
    
    return jsonify({'success': False, 'message': 'Link not found'})

@app.route('/api/links/<link_id>', methods=['DELETE'])
def delete_link(link_id):
    """删除链接"""
    data = load_data()
    data['links'] = [link for link in data['links'] if str(link['id']) != str(link_id)]
    save_data(data)
    return jsonify({'success': True})

@app.route('/api/categories', methods=['POST'])
def add_category():
    """添加分类"""
    data = load_data()
    category = request.json.get('name', '').strip()
    
    if category and category not in data['categories']:
        data['categories'].append(category)
        save_data(data)
        return jsonify({'success': True, 'categories': data['categories']})
    
    return jsonify({'success': False})

@app.route('/api/categories/<category>', methods=['DELETE'])
def delete_category(category):
    """删除分类"""
    data = load_data()
    
    # 检查是否有链接使用该分类
    used_by_links = any(link.get('category') == category for link in data['links'])
    if used_by_links:
        return jsonify({'success': False, 'message': '该分类正在被使用，无法删除'})
    
    if category in data['categories']:
        data['categories'].remove(category)
        save_data(data)
        return jsonify({'success': True, 'categories': data['categories']})
    
    return jsonify({'success': False})

@app.route('/api/categories/<category>', methods=['PUT'])
def update_category(category):
    """更新分类"""
    data = load_data()
    new_name = request.json.get('name', '').strip()
    
    if category in data['categories'] and new_name:
        # 更新所有使用该分类的链接
        for link in data['links']:
            if link.get('category') == category:
                link['category'] = new_name
        
        # 更新分类列表
        index = data['categories'].index(category)
        data['categories'][index] = new_name
        save_data(data)
        return jsonify({'success': True, 'categories': data['categories']})
    
    return jsonify({'success': False})

@app.route('/api/tags', methods=['POST'])
def add_tag():
    """添加标签"""
    data = load_data()
    tag = request.json.get('name', '').strip()
    
    if tag and tag not in data['tags']:
        data['tags'].append(tag)
        save_data(data)
        return jsonify({'success': True, 'tags': data['tags']})
    
    return jsonify({'success': False})

@app.route('/api/tags/<tag>', methods=['DELETE'])
def delete_tag(tag):
    """删除标签"""
    data = load_data()
    
    if tag in data['tags']:
        # 从所有链接中移除该标签
        for link in data['links']:
            if 'tags' in link and tag in link['tags']:
                link['tags'].remove(tag)
        
        data['tags'].remove(tag)
        save_data(data)
        return jsonify({'success': True, 'tags': data['tags']})
    
    return jsonify({'success': False})

@app.route('/api/tags/<tag>', methods=['PUT'])
def update_tag(tag):
    """更新标签"""
    data = load_data()
    new_name = request.json.get('name', '').strip()
    
    if tag in data['tags'] and new_name:
        # 更新所有使用该标签的链接
        for link in data['links']:
            if 'tags' in link and tag in link['tags']:
                index = link['tags'].index(tag)
                link['tags'][index] = new_name
        
        # 更新标签列表
        index = data['tags'].index(tag)
        data['tags'][index] = new_name
        save_data(data)
        return jsonify({'success': True, 'tags': data['tags']})
    
    return jsonify({'success': False})

@app.route('/api/export', methods=['GET'])
def export_data():
    """导出数据"""
    data = load_data()
    return jsonify(data)

@app.route('/api/import', methods=['POST'])
def import_data():
    """导入数据"""
    try:
        new_data = request.json
        if 'links' in new_data and 'categories' in new_data and 'tags' in new_data:
            save_data(new_data)
            return jsonify({'success': True})
        return jsonify({'success': False, 'message': '数据格式不正确'})
    except:
        return jsonify({'success': False, 'message': '导入失败'})

@app.route('/api/fetch-site-info', methods=['POST'])
def fetch_site_info():
    """获取网站信息"""
    try:
        data = request.json
        url = data.get('url', '').strip()
        
        if not url:
            return jsonify({'error': 'URL不能为空'}), 400
            
        # 添加协议头
        if not url.startswith(('http://', 'https://')):
            url = 'https://' + url
            
        try:
            import requests
            from bs4 import BeautifulSoup
            import urllib.parse
            
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
            }
            
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status()
            
            soup = BeautifulSoup(response.content, 'html.parser')
            
            # 获取网站名称
            title = ''
            og_title = soup.find('meta', property='og:title')
            if og_title and og_title.get('content'):
                title = og_title.get('content')
            else:
                title_tag = soup.find('title')
                if title_tag:
                    title = title_tag.get_text().strip()
            
            # 获取网站描述
            description = ''
            og_description = soup.find('meta', property='og:description')
            if og_description and og_description.get('content'):
                description = og_description.get('content')
            else:
                meta_description = soup.find('meta', attrs={'name': 'description'})
                if meta_description and meta_description.get('content'):
                    description = meta_description.get('content')
            
            # 获取网站图标
            icon = ''
            og_image = soup.find('meta', property='og:image')
            if og_image and og_image.get('content'):
                icon = og_image.get('content')
            else:
                # 尝试获取favicon
                favicon = soup.find('link', rel='icon')
                if favicon and favicon.get('href'):
                    icon = favicon.get('href')
                else:
                    # 构建默认favicon路径
                    parsed_url = urllib.parse.urlparse(url)
                    icon = f"{parsed_url.scheme}://{parsed_url.netloc}/favicon.ico"
            
            # 确保图标URL是绝对路径
            if icon and not icon.startswith('http'):
                parsed_url = urllib.parse.urlparse(url)
                if icon.startswith('/'):
                    icon = f"{parsed_url.scheme}://{parsed_url.netloc}{icon}"
                else:
                    icon = f"{parsed_url.scheme}://{parsed_url.netloc}/{icon}"
            
            return jsonify({
                'title': title or '未知网站',
                'description': description or '',
                'icon': icon or ''
            })
            
        except Exception as e:
            return jsonify({'error': '无法获取网站信息'}), 400
            
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)